<template>
  <div class="warehouse-warrant">
    <div class="card warehouse-warrant__header">
      <el-form inline>
        <el-form-item label="物品类型">
          <el-cascader
            v-model="params.goodsType"
            :options="goodsTypeOptions"
            :props="{ value: 'id', label: 'name' }"
            clearable
          />
        </el-form-item>

        <el-form-item label="入库时间">
          <el-date-picker
            v-model="params.entryTime"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd HH:mm:ss"
            :picker-options="pickerOptions"
          />
        </el-form-item>

        <el-form-item>
          <el-button
            size="medium"
            type="danger"
            @click="handleReset"
          >重置</el-button>

          <el-button
            size="medium"
            type="primary"
            @click="handleSearch"
          >查询</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="card warehouse-warrant__content">
      <div class="warehouse-warrant__content__header">
        <el-button
          type="primary"
          size="medium"
          @click="handleCreate"
        >
          创建入库单
        </el-button>
      </div>

      <el-table
        v-loading="loading"
        :data="listFormat"
        style="width: 100%"
        border
        stripe
      >
        <el-table-column
          prop="goodsType.name"
          label="物品类型"
          align="center"
        />

        <el-table-column
          prop="quantity"
          label="入库数量"
          align="center"
        />

        <el-table-column
          prop="unit_name"
          label="单位"
          align="center"
        />

        <el-table-column
          prop="conversion_ratio"
          label="单位换算比例(主/辅)"
          align="center"
        >
          <template v-slot="{ row }">
            {{ getConversionRatioFormat(row) }}
            <!--            {{ row.unit_id ? `${row.conversion_ratio} : 1` : '-' }}-->
          </template>
        </el-table-column>

        <el-table-column
          prop="unit_price"
          label="单价"
          align="center"
        />

        <!--        <el-table-column-->
        <!--          prop="total_amount"-->
        <!--          label="总价"-->
        <!--          align="center"-->
        <!--        />-->

        <!--        <el-table-column-->
        <!--          prop="entry_time"-->
        <!--          label="入库时间"-->
        <!--          align="center"-->
        <!--        />-->

        <el-table-column
          show-overflow-tooltip
          prop="remark"
          label="备注"
          align="center"
        />

        <el-table-column
          prop="photo"
          label="物品图片"
          align="center"
        >
          <template v-slot="{ row }">
            <el-image
              v-if="atLeastN(row.photo, 1)"
              style="width: 40px; height: 40px"
              :src="row.photo[0]"
              :preview-src-list="row.photo"
              fit="cover"
            />

            <el-tag v-else size="small" type="warning">未上传</el-tag>
          </template>
        </el-table-column>

        <el-table-column
          prop="handlerUser.username"
          label="经手人"
          align="center"
        />

        <!--        <el-table-column-->
        <!--          label="操作"-->
        <!--          align="center"-->
        <!--        >-->
        <!--          <template v-slot="{ row }">-->
        <!--            <el-button-->
        <!--              icon="el-icon-edit"-->
        <!--              type="text"-->
        <!--              @click="handleEdit(row)"-->
        <!--            >-->
        <!--              编辑-->
        <!--            </el-button>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
      </el-table>

      <div class="warehouse-warrant__content__pagination">
        <Pagination
          style="margin-top: 0; padding: 0;"
          :total="total"
          :limit="params.paginate"
          @pagination="pagination"
        />
      </div>
    </div>

    <WarehouseWarrantDialog
      ref="warehouseWarrantDialogRef"
      :visible.sync="visible"
      :model="model"
      :title="warehouseWarrantDialogTitle"
      :loading="btnLoading"
      :goods-type-options="goodsTypeOptions"
      @confirm="handleCreateConfirm"
    />
  </div>
</template>
<script>
import {
  getWarehouseWarrantList,
  getGoodsType,
  createWarehouseWarrant,
  editWarehouseWarrant
} from '@/api/officeSuppliesManagement'
import { atLeastN } from '@/utils/kris_utils'
import Pagination from '@/components/Pagination/index.vue'
import WarehouseWarrantDialog from '@/views/officeSuppliesManagement/components/WarehouseWarrantDialog.vue'
import { findAllParent } from '@/utils'
export default {
  name: '',
  components: {
    Pagination,
    WarehouseWarrantDialog
  },
  data() {
    return {
      list: [],
      params: {
        goodsType: '',
        entryTime: [],
        page: 1,
        paginate: 10
      },
      total: 0,
      goodsTypeOptions: [],
      loading: false,
      visible: false,
      model: {
        goods_type_id: null,
        quantity: 1,
        remark: '',
        unit_price: 1,
        total_amount: null,
        photo: [],
        unit_id: null
      },
      btnLoading: false,
      pickerOptions: {
        disabledDate(time) {
          const now = Date.now()
          return time.getTime() > now
        }
      }
    }
  },
  computed: {
    listFormat() {
      return this.list.map(item => {
        return {
          ...item,
          photo: this.parsePhoto(item.photo)
        }
      })
    },

    warehouseWarrantDialogTitle() {
      return this.model.id ? '修改入库单' : '创建入库单'
    }
  },
  created() {
    this.getWarehouseWarrantList()
    this.getGoodsType()
  },
  methods: {
    atLeastN,
    async getWarehouseWarrantList() {
      this.loading = true
      try {
        const res = await getWarehouseWarrantList(this.generateParams())
        this.list = res.data
        this.total = res.meta.total
      } catch (error) {
        this.$message.error(error?.response?.data?.message || '信息获取失败')
      } finally {
        await this.sleep()
        this.loading = false
      }
    },

    async getGoodsType() {
      try {
        const res = await getGoodsType()
        this.goodsTypeOptions = res.data
      } catch (error) {
        throw new Error(error?.response?.data?.message || '信息获取失败')
      }
    },

    generateParams() {
      const len = this.params.goodsType.length
      return {
        ...this.params,
        entryTime: this.params.entryTime && this.params.entryTime.length >= 1
          ? JSON.stringify(this.params.entryTime) : null,
        goodsType: len > 0 ? this.params.goodsType[len - 1] : null
      }
    },

    pagination(page) {
      this.params.page = page.page
      this.params.paginate = page.limit
      this.getWarehouseWarrantList()
    },

    parsePhoto(photo) {
      try {
        return JSON.parse(photo)
      } catch (error) {
        return []
      }
    },

    handleSearch() {
      this.params.page = 1
      this.getWarehouseWarrantList()
    },

    handleReset() {
      this.params = this.$options.data().params
      this.getWarehouseWarrantList()
    },

    sleep(t = 500) {
      return new Promise(resolve => setTimeout(resolve, t))
    },

    handleCreate() {
      this.visible = true
      this.$nextTick(() => {
        this.$refs.warehouseWarrantDialogRef.resetFields()
      })
    },

    async createWarehouseWarrant() {
      this.btnLoading = true
      try {
        const res = await createWarehouseWarrant(this.generateCreateParams())
        console.log('res --------->', res)
        this.$message.success('创建成功')
        this.visible = false
        this.refresh()
      } catch (error) {
        console.log('error --------->', error)
        this.$message.error(error?.response?.data?.message || '创建失败')
      } finally {
        this.btnLoading = false
      }
    },

    async editWarehouseWarrant() {
      this.btnLoading = true
      try {
        const res = await editWarehouseWarrant(this.generateCreateParams())
        this.$message.success('修改成功')
        this.visible = false
        this.refresh()
      } catch (error) {
        this.$message.error(error?.response?.data?.message || '修改失败')
      } finally {
        this.btnLoading = false
      }
    },

    handleCreateConfirm() {
      if (this.model.id) {
        this.editWarehouseWarrant()
      } else {
        this.createWarehouseWarrant()
      }
    },

    handleEdit(row) {
      this.model.id = row.id
      this.model.goods_type_id = this.goodsTypeIdFormat(row.goods_type_id)
      this.model.quantity = row.quantity
      this.model.unit_price = row.unit_price
      this.model.total_amount = row.total_amount
      this.model.remark = row.remark
      this.model.photo = row.photo
      this.visible = true
    },

    goodsTypeIdFormat(id) {
      const result = findAllParent(this.goodsTypeOptions, id)
      if (Array.isArray(result)) {
        result.push(id)
      }
      return result ?? []
    },

    generateCreateParams() {
      const len = this.model.goods_type_id.length
      return {
        ...this.model,
        photo: JSON.stringify(this.model.photo),
        goods_type_id: len > 0 ? this.model.goods_type_id[len - 1] : null
      }
    },

    refresh() {
      this.params = this.$options.data().params
      this.getWarehouseWarrantList()
    },

    getConversionRatioFormat(row) {
      const mainUnit = row?.goodsType?.goods_type_main_unit?.name
      return row?.unit_id ? `${row.conversion_ratio}${mainUnit} = 1${row.unit_name}` : '-'
    }
  }
}
</script>
<style lang="scss" scoped>
.warehouse-warrant {
  padding: 20px;

  &__header {
    ::v-deep(.el-form-item) {
      margin-bottom: 0;
      margin-right: 20px;
    }
  }

  &__content {

    &__header {
      margin-bottom: 20px;
    }

    &__pagination {
      margin-top: 20px;
      display: flex;
      justify-content: end;
    }
  }

  .card {
    padding: 20px;
    background-color: #fff;
    border-radius: 4px;
    margin-bottom: 20px;
  }

}
</style>
